import logging, os
from logging import handlers

DEFAULT_LEVEL = logging.INFO
DEBUG_LEVEL = logging.DEBUG
WARNING_LEVEL = logging.WARNING
ERROR_LEVEL = logging.ERROR
logger = logging.getLogger(__name__)
logger.setLevel(DEFAULT_LEVEL)
console_handler = None
time_file_handler = None
size_file_handler = None

fmt = '%(asctime)s [%(levelname)s] %(filename)s/line:%(lineno)d >> %(message)s'


def get_console_handler(level=DEFAULT_LEVEL, log_format=None):
    global console_handler
    if console_handler:
        return console_handler
    format_obj = logging.Formatter(log_format or fmt)  # 设置日志格式
    console = logging.StreamHandler()
    console.setFormatter(format_obj)
    console.setLevel(level)
    console_handler = console
    return console


def get_file_time_handler(log_name, when="midnight", interval=1, backup_count=30, encoding="utf-8", level=DEFAULT_LEVEL, log_format=None):
    global time_file_handler
    if time_file_handler:
        logger.info(f"get a exists time_file_handler ...")
        return time_file_handler
    format_obj = logging.Formatter(log_format or fmt)  # 设置日志格式
    f_log = handlers.TimedRotatingFileHandler(filename=log_name, when=when, interval=interval, backupCount=backup_count, encoding=encoding)
    f_log.setFormatter(format_obj)
    f_log.setLevel(level)
    time_file_handler = f_log
    return f_log


def get_file_size_handler(log_name, mode='a', max_bytes=0, backup_count=30, level=DEFAULT_LEVEL, log_format=None):
    global size_file_handler
    if size_file_handler:
        logger.info(f"get a exists size_file_handler ...")
        return size_file_handler
    format_obj = logging.Formatter(log_format or fmt)  # 设置日志格式
    f_log = handlers.RotatingFileHandler(filename=log_name, mode=mode, maxBytes=max_bytes, backupCount=backup_count)
    f_log.setFormatter(format_obj)
    f_log.setLevel(level)
    size_file_handler = f_log
    return f_log


def init_time_log(log_dir, log_name):
    log_file = os.path.join(log_dir, log_name)
    hdr = get_file_time_handler(log_file)
    # hdr = get_file_time_handler(log_file, when="S", interval=10, level=DEBUG_LEVEL)
    global logger
    logger.addHandler(hdr)


def init_size_log(log_dir, log_name, max_bytes=None):
    log_file = os.path.join(log_dir, log_name)
    if max_bytes:
        hdr = get_file_size_handler(log_file, max_bytes=max_bytes)
    else:
        hdr = get_file_size_handler(log_file)
    global logger
    logger.addHandler(hdr)


def init_error_log(log_dir, log_name, max_bytes=None):
    """返回处理异常的logger对象，按需取用"""
    err_log = logging.getLogger("error_log")
    err_log.setLevel(DEFAULT_LEVEL)
    log_file = os.path.join(log_dir, log_name)
    format_obj = logging.Formatter(fmt)
    hdr = handlers.RotatingFileHandler(filename=log_file, mode='a', maxBytes=max_bytes, backupCount=30)
    hdr.setFormatter(format_obj)
    hdr.setLevel(DEFAULT_LEVEL)
    err_log.addHandler(hdr)
    err_log.addHandler(get_console_handler())
    return err_log


logger.addHandler(get_console_handler())
